package com.skh.linkedlist;

/**
 * created by skh on 2019/6/15
 * 两两交换链表中的节点
 */
public class SwapPairs {
	/*
	Given a linked list, swap every two adjacent nodes and return its head.

	For example,
	Given1->2->3->4, you should return the list as2->1->4->3.
	 */

	public ListNode swapPairs(ListNode head) {

		ListNode pre = new ListNode(0);

		pre.next = head;

		ListNode temp = pre;

		while (temp.next != null && temp.next.next != null) {
			ListNode start = temp.next;
			ListNode end = temp.next.next;

			temp.next = end;
			temp = start;

			start.next = end.next;
			end.next = start;

		}


		return pre.next;


	}

	public static void main(String[] args) {
		ListNode listNode = ListNode.createListNode("1,2,3,4");
		SwapPairs swapPairs = new SwapPairs();
		ListNode listNode1 = swapPairs.swapPairs(listNode);
		ListNode.printListNode(listNode1);
	}

}
